using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Coderoom.ScrumPlanner.Domain.Validation
{
	internal sealed class EntityValidator
	{
		internal static ValidationResult Validate(Entity entity)
		{
			var result = new ValidationResult();

			var errors = (from prop in TypeDescriptor.GetProperties(entity).Cast<PropertyDescriptor>()
			              from attribute in prop.Attributes.OfType<ValidationAttribute>()
			              where !attribute.IsValid(prop.GetValue(entity))
			              select new ValidationError {PropertyName = prop.Name, Message = attribute.FormatErrorMessage(string.Empty), ValidationTarget = entity});

			result.Errors.AddRange(errors);
			result.IsValid = (result.Errors.Count == 0);

			return result;
		}
	}
}